<template>
	<view class="page-content">
		<default-navbar :pageTitle="formData.visitId ? '编辑拜访记录' : '新增拜访记录'"></default-navbar>
		<view class="page-main">
			<!--  errorType="toast" -->
			<up-form labelPosition="top" :model="formData" ref="formRef" labelWidth='300'
				:labelStyle="{ 'padding-left': '20rpx', 'font-weight': 'bold' }">
				<view class="projectInformation">
					<view class="title">
						<i class="iconfont icon-a-pinghangsibianxing2 red"></i>
						<view class="text">
							拜访记录
						</view>
						<i class="iconfont icon-a-pinghangsibianxing2 blue"></i>
					</view>
					<view class="main">
						<up-form-item label="项目名称" prop="projectId" required>
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择项目"
								v-model="formData.projectId" :localdata="projectList_data"></uni-data-select>
						</up-form-item>
						<up-form-item label="跟进日期" prop="visitDate" required>
							<view style="width: 100%;" @click="showFirstContactDate">
								<up-input readonly placeholder="请选择日期" v-model="formData.visitDate">
									<template v-slot:suffix>
										<view
											style="display: flex;flex-direction: row;align-items: center;justify-content: flex-start;">
											<up-icon name="calendar" size="24"></up-icon>
										</view>
									</template>
								</up-input>
							</view>
						</up-form-item>
						<up-form-item label="跟进内容" prop="visitContent" required>
							<up-textarea maxlength='-1' autoHeight placeholder="请输入跟进内容"
								v-model="formData.visitContent"></up-textarea>
						</up-form-item>
						<up-form-item label="意向度" prop="intentionLevel">
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择意向度"
								v-model="formData.intentionLevel"
								:localdata="intentionLevelList_data"></uni-data-select>
						</up-form-item>
						<up-form-item label="合作状态" prop="cooperationStatus">
							<uni-data-select :clear="true" style="width: 100%;" placeholder="请选择意向度"
								v-model="formData.cooperationStatus"
								:localdata="visit_cooperation_List_data"></uni-data-select>
						</up-form-item>
						<up-form-item label="备注" prop="remark">
							<up-textarea maxlength='-1' autoHeight placeholder="请输入备注"
								v-model="formData.remark"></up-textarea>
						</up-form-item>
					</view>
				</view>
			</up-form>
			<view class="operateRroup">
				<view class="confirm operateBtn">
					<up-button type="primary" text="完成并提交" color="#393e97" @click="confirmHandle"></up-button>
				</view>
				<view class="confirm operateBtn" v-if="formData.visitId && hasPermission('miniapp:visit:delete')">
					<up-button type="error" text="删除" color="red" @click="deleteItem(deleteVisitItem, formData.visitId, 2)"></up-button>
				</view>
			</view>
		</view>

		<!-- 首次接触时间 -->
		<up-datetime-picker ref="startDatePicker" :closeOnClickOverlay="true" format="YYYY-MM-DD" placeholder="请选择日期"
			:show="firstContactDate_visible" @close="firstContactDate_visible = false"
			@cancel="firstContactDate_visible = false" @confirm="firstContactDate_confirm" v-model="visitDateComputed"
			:minDate="minDate()" :maxDate="maxDate()" mode="date">

		</up-datetime-picker>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted, watch, computed } from "vue"
	import { onLoad } from "@dcloudio/uni-app";
	//组件
	import defaultNavbar from "@/components/defaultNavbar/index.vue";
	//api
	import { addVisit } from "@/api/addVisit/index"
	import { visitItem, deleteVisitItem } from "@/api/visitList/index"
	//hooks
	import useViewModel from './hooks/useViewModel'
	import useDataList from '@/appHooks/useDataList'
	import useAppHookds from "@/appHooks/useViewModel"
	const {
		rules,
		formData,
		minDate,
		maxDate,
		firstContactDate_visible,
		firstContactDate_confirm,
		showFirstContactDate,
	} = useViewModel()
	
	const {
		getProjectList,
		projectList_data
	} = useDataList()
	let {
		getVisit_cooperation_List,
		visit_cooperation_List_data,
		getIntentionLevelList,
		intentionLevelList_data,
		deleteItem,
		hasPermission
	} = useAppHookds()
	let formRef = ref(null) //form表单


	let startDatePicker = ref() //时间选择器ref
	//时间选择器回显
	let visitDateComputed = computed({
		get() {
			let { visitDate } = formData.value
			if (!visitDate) {
				return new Date().getTime()
			} else {
				return new Date(visitDate).getTime()
			}
		},
		set(val) {
			const ts = val < 1e12 ? val * 1000 : val;
			const date = new Date(ts);
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			formData.value.visitDate = `${year}-${month}-${day}`
		}
	})



	//提交表单
	let addVisitHandle = () : void => {
		for(let i in formData.value){
			if(!formData.value[i]){
				delete formData.value[i]
			}
		}
		addVisit(formData.value).then(res => {
			let { code, visitId } = res as any
			if (code == 200) {
				uni.showToast({
					title: '提交成功!'
				})
				setTimeout(() => {
					uni.navigateTo({
						url: `/pages/visitItemDetail/visitItemDetail?visitId=${visitId}`
					})
				}, 1000)
			}
		})
	}

	//提交表单
	let confirmHandle = () : void => {
		formRef.value.validate().then(valid => {
			if (valid) {
				addVisitHandle()
			} else {
			}
		}).catch((err) => {
			// 处理验证错误  
			let [target] = err
			if (target) {
				uni.showToast({
					title: target.message,
					icon: 'none'
				})
			}
		});
	}

	//获取详情
	let getVisitItem = (visitId : string) : void => {
		visitItem(visitId).then(res => {
			let { data } = res as any
			// data.ourCompany = String(data.ourCompany)
			formData.value = data
		})
	}

	//获取详情 - 编辑的场景
	onLoad((e) => {
		let { visitId, projectId } = e as any
		if (visitId) {
			getVisitItem(visitId)
		}

		if (projectId) {
			formData.value.projectId = projectId
		}
	})
	onMounted(() => {
		formRef.value.setRules(rules)
		getIntentionLevelList()
		getVisit_cooperation_List()
		getProjectList()
		startDatePicker.value.innerValue = new Date().getTime();
	})
</script>

<script lang="ts">
	export default {
		options: {
			styleIsolation: 'shared',
		}
	}
</script>

<style lang="scss" scoped>
	.page-content {
		width: 100%;
		height: 100%;
		background: rgb(246, 246, 248);

		.page-main {
			display: block;
			flex: 1;
			width: 100%;
			padding: 20rpx;
			box-sizing: border-box;

			.projectInformation {
				background: #fff;
				border-radius: 6rpx;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
				margin-bottom: 20rpx;
			}

			.operateRroup {
				margin: 40rpx;
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: space-around;

				.operateBtn {
					width: 50%;
					padding: 0 20rpx;
					box-sizing: border-box;
				}
			}

			.title {
				text-align: center;
				font-weight: bold;
				padding: 30rpx 0;
				border-bottom: 2rpx solid rgba(235, 235, 237, 0.5);
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;

				.red {
					color: #ec2f8a;
				}

				.blue {
					color: #364094;
				}

				.text {
					margin: 0 20rpx;
				}
			}

			.main {
				padding: 20rpx;
				box-sizing: border-box;
			}
		}



		::v-deep .u-form-item__body__left__content__required {
			left: 0;
		}
	}
</style>